package com.will.txj.aj.global.exception;

import com.will.txj.common.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author: wen-yi;
 * @date: 2021/12/3 23:31;
 * @Description: 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕捉参数校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public R handleMethodArgumentNotValidException(BindException e){
        String field = e.getBindingResult().getFieldError().getField();
        String error = e.getBindingResult().getFieldError().getDefaultMessage();
        log.error("field: {}, error: {}", field,error);
        return R.fail().setCode(HttpStatus.BAD_REQUEST.value()).setMessage(field+":"+error);
    }

    /**
     * 捕捉参数校验异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String field = e.getBindingResult().getFieldError().getField();
        String error = e.getBindingResult().getFieldError().getDefaultMessage();
        log.error("field: {}, error: {}", field,error);
        return R.fail().setCode(HttpStatus.BAD_REQUEST.value()).setMessage(field+":"+error);
    }

    /**
     * 捕捉其他所有异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Object globalExceptionHandler(Exception e) {
        //e.printStackTrace();
        log.error("ex: {}", e.getMessage());
        String _message = StringUtils.hasText(e.getMessage()) ? e.getMessage() : e.toString();
        if (e.getCause() != null) {
            _message = e.getCause().getMessage();
        }
        _message = _message.length() > 1000 ? _message.substring(0, 1000) : _message;
        return R.fail().setCode(HttpStatus.INTERNAL_SERVER_ERROR.value()).setMessage(_message);
    }
}
